package com.thinkfit.jy.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothClass;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.net.NetworkInfo;
import android.net.wifi.SupplicantState;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;

import com.common.lib.constant.Constants;
import com.common.lib.constant.EventBusEvent;
import com.common.lib.fragment.BaseFragment;
import com.common.lib.mvp.contract.EmptyContract;
import com.common.lib.mvp.presenter.EmptyPresenter;
import com.jaygoo.widget.OnRangeChangedListener;
import com.jaygoo.widget.RangeSeekBar;
import com.thinkfit.jy.R;
import com.thinkfit.jy.activity.SettingNewOtherActivity;
import com.thinkfit.jy.ble.bluetooth.BluetoothHelper;
import com.thinkfit.jy.ble.bluetooth.interfaces.IBTStateListener;
import com.thinkfit.jy.ble.bluetooth.interfaces.IBluetoothHelper;
import com.thinkfit.jy.bluetooth.Bluetooth;
import com.thinkfit.jy.utils.BluetoothOrder;
import com.thinkfit.jy.utils.DateUtils;
import com.thinkfit.jy.utils.SystemUtils;
import com.thinkfit.jy.utils.ToastUtils;
import com.thinkfit.jy.utils.WifiSupport;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * 关于界面
 */
public class SystemSettingFragment extends BaseFragment<EmptyContract.Presenter> implements EmptyContract.View {


    ImageView ivWlanSwitch, ivBluetoothSwitch;
    TextView tvWlan, tvBluetooth, tvBrigthnessNum, tvSoundNum;
    LinearLayout llWlan, llBluetooth;
    RangeSeekBar rsbBrigthness, rsbSound;

    private AudioManager mAudioManager;

    int mBrigthnessProgress, mSoundProgress, brigthnessProgress, volumeProgress;
    WifiManager wifiManager;
    boolean isBluetoothOpened, isWifiOpened;
    boolean isFirstBrigthness = true;
    boolean isFirstSound = true;

    public static SystemSettingFragment getInstance(int index) {
        Bundle bundle = new Bundle();
        bundle.putInt(Constants.BUNDLE_EXTRA, index);
//        bundle.putInt(Constants.BUNDLE_EXTRA_2, type);
        SystemSettingFragment fragment = new SystemSettingFragment();
        fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_system_setting;
    }

    @Override
    protected void initView(@NonNull View view, @Nullable Bundle savedInstanceState) {
        setViewsOnClickListener(R.id.iv_wlan_switch, R.id.ll_wlan, R.id.iv_bluetooth_switch, R.id.ll_bluetooth);
        ivWlanSwitch = view.findViewById(R.id.iv_wlan_switch);
        llWlan = view.findViewById(R.id.ll_wlan);
        tvWlan = view.findViewById(R.id.tv_wlan);
        ivBluetoothSwitch = view.findViewById(R.id.iv_bluetooth_switch);
        llBluetooth = view.findViewById(R.id.ll_bluetooth);
        tvBluetooth = view.findViewById(R.id.tv_bluetooth);
        rsbBrigthness = view.findViewById(R.id.rsb_brigthness);
//        tvBrigthnessNum = view.findViewById(R.id.tv_brigthness_num);
        rsbSound = view.findViewById(R.id.rsb_sound);
//        tvSoundNum = view.findViewById(R.id.tv_sound_num);

        wifiManager = (WifiManager) getContext().getSystemService(Context.WIFI_SERVICE);
        isWifiOpened = isWifiOpened();
        resetSwitch(ivWlanSwitch, isWifiOpened);

        int currentBrigthness = SystemUtils.getBrightness(getContext());
        //最大亮度
        int mMaxBrigthness = SystemUtils.getMaxBrightness(getContext());
        brigthnessProgress = (int) ((currentBrigthness / (mMaxBrigthness * 1f)) * 100f);
        HashMap<Object, Object> map = new HashMap<>();
        rsbBrigthness.setRange(0, 100);
        rsbBrigthness.setProgress(brigthnessProgress);
//        tvBrigthnessNum.setText(brigthnessProgress+"%");
        rsbBrigthness.setOnRangeChangedListener(new OnRangeChangedListener() {
            @Override
            public void onRangeChanged(RangeSeekBar view, float leftValue, float rightValue, boolean isFromUser) {
                if (isFirstBrigthness) {
                    isFirstBrigthness = false;
                    return;
                }

                mBrigthnessProgress = (int) (leftValue + 0.0001);
//                tvBrigthnessNum.setText(mBrigthnessProgress+"%");
                int brigthnessVolume = (int) ((mMaxBrigthness / 100f) * mBrigthnessProgress);

                map.clear();
                map.put(EventBusEvent.BRIGHTNES_CHANGE, brigthnessVolume);
                EventBus.getDefault().post(map);
            }

            @Override
            public void onStartTrackingTouch(RangeSeekBar view, boolean isLeft) {

            }

            @Override
            public void onStopTrackingTouch(RangeSeekBar view, boolean isLeft) {

            }
        });
        int currentVolume = getAudioManager().getStreamVolume(AudioManager.STREAM_MUSIC);
        //媒体音量 STREAM_MUSIC    STREAM_RING 铃声音量
        int mMaxVolume = getAudioManager().getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        volumeProgress = (int) ((currentVolume / (mMaxVolume * 1f)) * 100f);
        rsbSound.setRange(0, 100);
        rsbSound.setProgress(volumeProgress);
//        tvSoundNum.setText(volumeProgress +"%");
        rsbSound.setOnRangeChangedListener(new OnRangeChangedListener() {
            @Override
            public void onRangeChanged(RangeSeekBar view, float leftValue, float rightValue, boolean isFromUser) {
                if (isFirstSound) {
                    isFirstSound = false;
                    return;
                }
                mSoundProgress = (int) (leftValue + 0.0001);
//                tvSoundNum.setText(mSoundProgress+"%");

                int volume = (int) ((mMaxVolume / 100f) * mSoundProgress);

                map.clear();
                map.put(EventBusEvent.VOICE_CHANGE, volume);
                EventBus.getDefault().post(map);
                if (volume <= 0) {
                    getAudioManager().setRingerMode(AudioManager.RINGER_MODE_SILENT);
                } else {
                    getAudioManager().setRingerMode(AudioManager.RINGER_MODE_NORMAL);

                }
                //设置铃声音量
                getAudioManager().setStreamVolume(AudioManager.STREAM_MUSIC, volume, 0);

            }

            @Override
            public void onStartTrackingTouch(RangeSeekBar view, boolean isLeft) {

            }

            @Override
            public void onStopTrackingTouch(RangeSeekBar view, boolean isLeft) {

            }
        });

    }

    public void resetSwitch(ImageView view, boolean isSwitch) {
        if (isSwitch) {
            view.setImageResource(R.drawable.img_set_switch_open);
        } else {
            view.setImageResource(R.drawable.img_set_switch_close);
        }
    }

    /**
     * 判断wifi是否已经打开
     * @return true：已打开、false:未打开
     */
    public boolean isWifiOpened() {
        int status = wifiManager.getWifiState();
        if (status == WifiManager.WIFI_STATE_ENABLED) {
            //wifi已经打开
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        isBluetoothOpened = Bluetooth.getInstance().isBluetoothOpened();
        resetSwitch(ivBluetoothSwitch, isBluetoothOpened);
        WifiManager wifiManager = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();

        String ssid = wifiInfo.getSSID().replace("\"", "");
        if (ssid.equals("<unknown ssid>")) {
            tvWlan.setText(R.string.app_not_connect);
        } else {
            tvWlan.setText(ssid);
        }
        rsbBrigthness.setProgress(brigthnessProgress);
        rsbSound.setProgress(volumeProgress);

        refreshBleName(false);
//        if(BluetoothOrder.getInstance().isConnect()){
//            String bluetoothName = BluetoothOrder.getInstance().getBluetoothName();
//            tvBluetooth.setText(bluetoothName);
//        }else {
//            tvBluetooth.setText(getString(R.string.app_not_connect));
//        }
    }

    @Override
    public void onStop() {
        super.onStop();
        isFirstSound = true;
        isFirstBrigthness = true;
//        DeviceTypeUtils.showBackButton(getContext().getApplicationContext());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        closeConcealButton();
    }

    @Override
    public void onReceive(@NonNull HashMap<String, Object> map) {
        if(map.containsKey(EventBusEvent.REFRESH_BLUETOOTH)){
            String bluetoothName = BluetoothOrder.getInstance().getBluetoothName();
            if(BluetoothOrder.getInstance().isConnect()){
                tvBluetooth.setText(bluetoothName);
            }else {
                tvBluetooth.setText(getString(R.string.app_not_connect));
            }

        }else if(map.containsKey(EventBusEvent.BLUETOOTH_CHANGE)){
            boolean o = (boolean) map.get(EventBusEvent.BLUETOOTH_CHANGE);
            refreshBleName(o);
        }
        super.onReceive(map);
    }

    Disposable refreshBleDisposable;
    @SuppressLint("MissingPermission")
    public void refreshBleName(boolean isDelay){
        closeConcealButton();
        if(isDelay){
            refreshBleDisposable = Observable.timer(4, TimeUnit.SECONDS)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<Long>() {
                        @Override
                        public void accept(Long aLong) throws Exception {
                            List<BluetoothDevice> bleConnectDevice = BluetoothOrder.getInstance().getBleConnectDevice(getContext());
                            if (bleConnectDevice.size() > 0) {
                                for (BluetoothDevice item : bleConnectDevice) {
                                    if(item.getBluetoothClass() == null){
                                        closeConcealButton();
                                        return;
                                    }
                                    int styleMajor = item.getBluetoothClass().getMajorDeviceClass();//获取蓝牙主要分类
                                    if(BluetoothClass.Device.Major.AUDIO_VIDEO == styleMajor){
                                        tvBluetooth.setText(item.getName());
                                        closeConcealButton();
                                        return;
                                    }

                                }

                            }else {
                                tvBluetooth.setText(getString(R.string.app_not_connect));
                            }
                            closeConcealButton();
                        }
                    });

        }else {
            List<BluetoothDevice> bleConnectDevice = BluetoothOrder.getInstance().getBleConnectDevice(getContext());
            if (bleConnectDevice.size() > 0) {
                for (BluetoothDevice item : bleConnectDevice) {
                    if(item.getBluetoothClass() == null){
                        closeConcealButton();
                        return;
                    }
                    int styleMajor = item.getBluetoothClass().getMajorDeviceClass();//获取蓝牙主要分类
                    if(BluetoothClass.Device.Major.AUDIO_VIDEO == styleMajor){
                        tvBluetooth.setText(item.getName());
                        closeConcealButton();
                        return;
                    }

                }

            }else {
                tvBluetooth.setText(getString(R.string.app_not_connect));
            }
        }

    }

    public void closeConcealButton(){
        if(refreshBleDisposable != null){
            refreshBleDisposable.dispose();
            refreshBleDisposable = null;
        }
    }

    private AudioManager getAudioManager() {
        if (mAudioManager == null) {
            mAudioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
        }
        return mAudioManager;
    }

    @NonNull
    @Override
    protected EmptyContract.Presenter onCreatePresenter() {
        return new EmptyPresenter(this);
    }

    @Override
    public void onClick(View v) {
        Bundle bundle = null;
        switch (v.getId()) {
            case R.id.iv_wlan_switch:
//                if(delayonnectingPoint()){
//                    return;
//                }
                if(isWifiOpened()){
                    isWifiOpened = false;
                    //关闭wifi
                    wifiManager.setWifiEnabled(false);
                    tvWlan.setText(getString(R.string.app_not_connect));
                }else {
                    isWifiOpened = true;
                    //打开wifi
                    wifiManager.setWifiEnabled(true);
                }
                System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa  isWifiOpened : "+isWifiOpened());
                resetSwitch(ivWlanSwitch,isWifiOpened);
                HashMap<String, Object> map = new HashMap<>();
                map.put(EventBusEvent.WIFI_CHANGE,isWifiOpened);
                EventBus.getDefault().post(map);
                break;
            case R.id.ll_wlan:
                if(!isWifiOpened()){
                    ToastUtils.getInstance().show(getContext(),getString(R.string.app_wlan_open_tip));
                    return;
                }
                bundle = new Bundle();
                bundle.putInt(Constants.BUNDLE_EXTRA, SettingNewOtherActivity.WIFI);
                openActivity(SettingNewOtherActivity.class,bundle);
                break;
            case R.id.iv_bluetooth_switch:
//                if(delayonnectingPoint()){
//                    return;
//                }
                map = new HashMap<>();
                boolean bluetoothOpened = Bluetooth.getInstance().isBluetoothOpened();
                if (Bluetooth.getInstance().isBluetoothOpened()) {
                    isBluetoothOpened = false;
//                    mBluetoothHelper.close();
                    boolean b = Bluetooth.getInstance().closeBluetooth();
                    resetSwitch(ivBluetoothSwitch,isBluetoothOpened);
                    map.put(EventBusEvent.BLUETOOTH_CHANGE, false);
                } else {
                    isBluetoothOpened = true;
//                    mBluetoothHelper.open();
                    boolean b = Bluetooth.getInstance().openBluetooth();
                    resetSwitch(ivBluetoothSwitch,isBluetoothOpened);
                    map.put(EventBusEvent.BLUETOOTH_CHANGE, true);
                }
                EventBus.getDefault().post(map);
                if(!isBluetoothOpened){
                    tvBluetooth.setText(getString(R.string.app_not_connect));
                }
                break;
            case R.id.ll_bluetooth:
                bundle = new Bundle();
                bundle.putInt(Constants.BUNDLE_EXTRA, SettingNewOtherActivity.BLUETOOTH);
                openActivity(SettingNewOtherActivity.class,bundle);
                break;
        }
    }
    long currentTime = 0;
    public boolean delayonnectingPoint(){
        Date date = new Date();
        if((date.getTime()-currentTime) < 2000){
            return true;
        }
        currentTime = date.getTime();
        return false;
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onBroadcastReceive(Intent intent) {
        if (getView() == null) {
            return;
        }
        if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(intent.getAction())) {
            int state = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);
            switch (state) {
                case WifiManager.WIFI_STATE_DISABLED: {
                    Log.d(TAG, "已经关闭");
                    isWifiOpened = false;
                    break;
                }
                case WifiManager.WIFI_STATE_DISABLING: {
                    Log.d(TAG, "正在关闭");
                    break;
                }
                case WifiManager.WIFI_STATE_ENABLED: {
                    Log.d(TAG, "已经打开");
                    isWifiOpened = true;
//                    sortScaResult();
                    break;
                }
                case WifiManager.WIFI_STATE_ENABLING: {
                    Log.d(TAG, "正在打开");
                    break;
                }
                case WifiManager.WIFI_STATE_UNKNOWN: {
                    Log.d(TAG, "未知状态");
                    break;
                }
            }
        } else if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(intent.getAction())) {
            NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
            intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE);
            if (NetworkInfo.State.DISCONNECTED == info.getState()) {//wifi没连接上
                Log.d(TAG, "wifi没连接上");

            } else if (NetworkInfo.State.CONNECTED == info.getState()) {//wifi连接上了
                Log.d(TAG, "wifi连接上了");
                WifiInfo connectedWifiInfo = WifiSupport.getConnectedWifiInfo(getActivity());
                //连接成功 跳转界面 传递ip地址
                tvWlan.setText(connectedWifiInfo.getSSID().replace("\"", ""));

                dismissProgressDialog();
            } else if (NetworkInfo.State.CONNECTING == info.getState()) {//正在连接
                Log.d(TAG, "wifi正在连接");
                WifiInfo connectedWifiInfo = WifiSupport.getConnectedWifiInfo(getActivity());

            }
        } else if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(intent.getAction())) {
//            isWifiChange = true;
        } else if (WifiManager.SUPPLICANT_STATE_CHANGED_ACTION.equals(intent.getAction())) {
            SupplicantState state = intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE);
            switch (state) {//TODO Setting文件里面代码，网络状态监听变化 断开、连接、密码错误的操作全在这里进行
                case ASSOCIATING://申请连接中
//                    mWasAssociating = true;
                    break;
                case ASSOCIATED:
//                    mWasAssociated = true;
                    break;
                case COMPLETED://连接成功后进入
//                    isExit = false;
                    isWifiOpened = false;
                    WifiInfo connectedWifiInfo = WifiSupport.getConnectedWifiInfo(getActivity());
                    //连接成功 跳转界面 传递ip地址
                    tvWlan.setText(connectedWifiInfo.getSSID().replace("\"", ""));
                    dismissProgressDialog();
                    HashMap<String, Object> map = new HashMap<>();
                    map.put(EventBusEvent.REFRESH_WIFI,0);
                    EventBus.getDefault().post(map);
                    break;
                case DISCONNECTED://断开连接后进入dormant判断是密码错误还是其他连接错误
                case DORMANT:
                    tvWlan.setText(getString(R.string.app_not_connect));
                    isWifiOpened = false;
//                    if (mWasAssociated || mWasHandshaking) {
//                        if (mConnectType != 0) {
//                            //解绑
//                            mConnectType = 0;
//                            WifiSupport.doDisconnectWifi("\"" + mConnectionWifi.getWifiName() + "\"", getActivity());
//                            sortScaResult();
//                            dismissProgressDialog();
//                            Intent i = new Intent(getActivity(), DialogActivity.class);
//                            i.putExtra(Constants.BUNDLE_EXTRA, DialogActivity.SHOW_INPUT_WIFI_PSW_DIALOG);
//                            i.putExtra(Constants.BUNDLE_EXTRA_2, mConnectionWifi.getWifiName());
//                            mLauncher.launch(i);
//                            showToast(R.string.app_check_wifi_password);
//                        }
//                    }
                    break;
                case INTERFACE_DISABLED:
                case UNINITIALIZED:
                    break;
                case FOUR_WAY_HANDSHAKE://四次握手进入连接
                case GROUP_HANDSHAKE:
//                    mWasHandshaking = true;
                    break;
            }
        }
    }
}
